package ThreadRelated

import "fmt"

// PrintAlternate2
// @author: liujun
// @date: 2022/4/2322:53
// @author—Email: ljfirst@mail.ustc.edu.cn
// @description:
// @blogURL: https://leetcode-cn.com/problems/print-zero-even-odd/
type PrintAlternate2 struct {
}

var (
	zeroMsg = make(chan int, 0)
	oddMsg  = make(chan int, 0)
	evenMsg = make(chan int, 0)
	n       int
)

func (p *PrintAlternate2) Print(num int) {
	n = num
	wg.Add(num)

	go p.PrintZero()
	go p.PrintOdd()
	go p.PrintEven()
	zeroMsg <- 0

	wg.Wait()
}

func (p *PrintAlternate2) PrintZero() {
	defer wg.Done()
	for {
		key := <-zeroMsg
		if key > n {
			fmt.Println("end when comes to zero")
			return
		}
		fmt.Print(fmt.Sprintf("0%d", key))
		oddMsg <- key + 1
	}
}

// PrintEven 输出偶数
func (p *PrintAlternate2) PrintEven() {
	defer wg.Done()
	for {
		key := <-evenMsg
		if key > n {
			fmt.Println("end when comes to even")
			return
		}
		fmt.Print(fmt.Sprintf("0%d", key))
		oddMsg <- key + 1
	}
}

func (p *PrintAlternate2) PrintOdd() {
	defer wg.Done()
	for {
		key := <-oddMsg
		if key > n {
			fmt.Println("end when comes to odd")
			return
		}
		fmt.Print(fmt.Sprintf("0%d", key))
		evenMsg <- key + 1
	}
}
